package com.zy.cat.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.zy.cat.common.utils.sms.RYSMSUtils;
import com.zy.cat.entity.app.CatAppNotice;
import com.zy.cat.entity.app.CatAppUseVideo;
import com.zy.cat.entity.app.repository.CatAppNoticeRepository;
import com.zy.cat.entity.app.repository.CatAppVideoRepository;
import com.zy.cat.entity.app.resp.CatAppConfigInfoResp;
import com.zy.cat.entity.app.resp.CatAppConfigInfoResp.BottomButton;
import com.zy.cat.entity.app.resp.CatAppConfigInfoResp.HeaderLogoButton;
import com.zy.cat.entity.app.resp.CatAppConfigInfoResp.HomeDialogConfig;
import com.zy.cat.entity.app.resp.CatAppConfigInfoResp.SideButton;
import com.zy.cat.entity.app.resp.CatAppGoodsMsgResp;
import com.zy.cat.entity.app.resp.CatAppMessageResp;
import com.zy.cat.entity.app.resp.CatAppNoticeResp;
import com.zy.cat.entity.app.resp.CatAppVersionInfoResp;
import com.zy.cat.entity.app.resp.NewItemResp;
import com.zy.cat.entity.dev.CatDevUserInfo;
import com.zy.cat.entity.dev.repository.CatDevUserInfoRepository;
import com.zy.cat.service.CacheService;
import com.zy.cat.service.CatUtilsService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CatUtilsServiceImpl implements CatUtilsService {

	private static final String APP_BOTTON_CONFIG_KEY = "CAT_APP_BOTTON_CONFIG";

	@Autowired
	CacheService cacheService;

	@Autowired
	@Qualifier("redis8")
	RedisTemplate<String, String> redis8;

	@Autowired
	@Qualifier("redis6")
	RedisTemplate<String, String> redis6;

	@Autowired
	CatDevUserInfoRepository catDevUserInfoRepository;

	@Autowired
	CatAppNoticeRepository catAppNoticeRepository;

	@Autowired
	CatAppVideoRepository appVideoRepository;

	@Autowired
	@Qualifier("redis15")
	RedisTemplate<String, Object> redis15;

	@Override
	public boolean sendMsg(int stype, String phone, String sign) {
		String key = "CAT_BING_PHONE";
		if (stype == 1) {
			key = "CAT_BING_PHONE";
		}
		String code = (int) ((Math.random() * 9 + 1) * 1000) + "";
		/* 2020-03-05 改为花生狗公众号一样的账号 */
		if (RYSMSUtils.getInstance(1).sendCodeMS(phone, code, sign)) {
			redis8.opsForValue().set(key + "_" + phone + "_" + code, LocalDateTime.now().toString(), 5,
					TimeUnit.MINUTES);
			return true;
		}
		return false;
	}

	@Override
	@Transactional
	public String test(String pid) {
		CatDevUserInfo userInfo = catDevUserInfoRepository.findByPid(pid);
		userInfo.setNikename("沙发沙发沙发");
		String result = JSON.toJSONString(userInfo);
		log.info("--->" + result);
//		int ss=100/0;
		return result;
	}

	@Override
	public CatAppVersionInfoResp checkAppVersion(Integer rtype, Integer appId, String brand, String model,
			String vscode, String cid) {
		CatAppVersionInfoResp resp = cacheService.getLastAppVersion(rtype, appId, "official-001");
		if (resp == null) {
			return null;
		}
		if (Integer.parseInt(vscode) < Integer.parseInt(resp.getVscode())) {
			return resp;
		}
		return null;
	}

	@Override
	public CatAppNoticeResp getMessageInfo(Integer rtype, String pid) {
		List<CatAppNotice> list = catAppNoticeRepository.findByMstatus(1);
		if (list == null || list.size() < 1) {
			return null;
		}
		// 从集合中随机抽取
		Random random = new Random();
		CatAppNoticeResp resp = new CatAppNoticeResp();
		BeanUtils.copyProperties(list.get(random.nextInt(list.size())), resp);
		return resp;
	}

	@Override
	public CatAppConfigInfoResp getAppConfigInfo(Integer rtype, Integer appId, String version, String cid) {
		CatAppVersionInfoResp appVersion = checkAppVersion(rtype, appId, "", "", version, cid);
		CatAppConfigInfoResp resp = CatAppConfigInfoResp.builder().version(appVersion).build();
		// 登录方式控制
		String key = "CAT_DEV_LOGIN_MODE_KEY";
		String hashKey = (rtype == 0 ? "Android" : "IOS") + "_" + appId;
		if (redis15.hasKey(key) && StringUtils.equals((String) redis15.opsForHash().get(key, hashKey), version)) {
			resp.setLoginMode(1);
		}
		resp.setSplashImg("http://");

		String configByAppId = rtype + "_" + appId;
		BottomButton bottomButton;
		// 查询，该appId下是否有
		if (!redis6.opsForHash().hasKey(APP_BOTTON_CONFIG_KEY, configByAppId)) {
			// 没有则新建
			bottomButton = createDefaultButtonConfig(rtype, appId);
			// 将对象存入本渠道
			redis6.opsForHash().put(APP_BOTTON_CONFIG_KEY, configByAppId, JSON.toJSONString(bottomButton));
		} else {
			bottomButton = JSON.parseObject((String) redis6.opsForHash().get(APP_BOTTON_CONFIG_KEY, configByAppId),
					BottomButton.class);
		}
		// 中间按钮
		resp.setMainBtn(bottomButton);

		// 设置广告状态
		resp.setAdStatus(cacheService.getCatAppAdStatus(rtype, cid, version));

		// 个人中心页，设置侧悬浮按钮
		SideButton sideButton = new SideButton();
		sideButton.setIndex(1);
		sideButton.setFullScreen(1);
		sideButton.setIconUrl("https://img.jiuqumao.cn/imgs/btm_icon/ic_my_side_5088.png");
		sideButton.setPageType(1);
		if (rtype == 0) {
			sideButton.setPageUrl("https://game.jiuqumao.cn/mall/Invite/Invite");
		} else {
			sideButton.setPageUrl("https://ttj.jiuqumao.cn/mall/Invite/Invite");
		}
		sideButton.setRequestParams(new String[] { "rtype", "pid", "utoken", "headerShow" });
		resp.setCenterSideBtn(sideButton);

		// 首页，设置侧悬浮按钮
		SideButton myButton = new SideButton();
		myButton.setIndex(0);
		myButton.setFullScreen(1);
		myButton.setIconUrl("https://img.jiuqumao.cn/imgs/btm_icon/ic_my_side_5088.png");
		myButton.setPageType(1);
		Date dateFormat = new Date(2020 - 1900, 12 - 1, 13);
		if (new Date().before(dateFormat)) {
			myButton.setIconUrl("https://img.jiuqumao.cn/imgs/btm_icon/ic_main_slide1212.webp");
			myButton.setPageUrl("https://s.click.taobao.com/II4bdtu");
		}
		myButton.setPageUrl("");
		resp.setHomeSideBtn(myButton);

		// 首页，增加首页弹窗标识
		HomeDialogConfig homedialogConfig = new HomeDialogConfig();
		homedialogConfig.setName("超级红包");
		// if(new Date().before(dateFormat)) {
		homedialogConfig.setIconUrl("https://img.jiuqumao.cn/imgs/20210308popup.png");
		homedialogConfig.setPageType(3);
		homedialogConfig.setPageUrl("https://s.click.taobao.com/ot5Nqqu");
		if (new Date().getTime() < 1615219199000L) {
			resp.setHomeDialogConfig(homedialogConfig);
		}

		// 配置显示首页头部样式
		HeaderLogoButton headerLogoButton = new CatAppConfigInfoResp.HeaderLogoButton();
		headerLogoButton.setName("邀请好友");
		if (rtype == 0) {
			headerLogoButton.setPageUrl("https://game.jiuqumao.cn/mall/Invite/Invite");
		} else {
			headerLogoButton.setPageUrl("https://ttj.jiuqumao.cn/mall/Invite/Invite");
		}
		headerLogoButton.setFullScreen(1);
		headerLogoButton.setIconUrl("https://img.jiuqumao.cn/imgs/8ad43ad3538b12d1bd46013852f0ca42.webp");
		headerLogoButton.setRequestParams(new String[] {});
		headerLogoButton.setWidthRatio(0.40);
		headerLogoButton.setHeightRatio(-2.0);
		if (appId == 1) {
			headerLogoButton.setName("新手教程");
			headerLogoButton.setPageUrl("https://ttj.jiuqumao.cn/mall/course/course");
			headerLogoButton.setIconUrl("https://img.jiuqumao.cn/imgs/6fca9d251495aa2443b1c3fceec80107.webp");
			headerLogoButton.setFullScreen(0);
		}
		resp.setHeaderLogoBtn(headerLogoButton);
		return resp;
	}

	/**
	 * 创建一个默认的按钮配置
	 * 
	 * @author lipengchao
	 * @date 2020-05-29 03:30:42
	 * @param appId
	 * @return
	 */
	private BottomButton createDefaultButtonConfig(Integer rtype, Integer appId) {
		// 生成默认，存入缓存
		CatAppConfigInfoResp.BottomButton button = new BottomButton();
		if (rtype == 0) {
			button.setIconUrl("https://img.jiuqumao.cn/imgs/btm_icon/" + (appId == 0 ? "btm_mfc.png" : "btm_mfc.png"));
		} else {
			button.setIconUrl("https://img.jiuqumao.cn/imgs/btm_icon/btm_mfc_ios_dark.png");
			button.setIconDarkUrl("https://img.jiuqumao.cn/imgs/btm_icon/btm_mfc_ios_dark.png");
		}
		button.setIndex(2);
		button.setName("免费抽");
		if (appId == 0) {
			button.setPageUrl("https://game.jiuqumao.cn/mall/mfc/mfc");
		} else {
			button.setPageUrl("https://ttj.jiuqumao.cn/mall/mfc/mfc");
		}
		button.setRefresh(1);
		button.setRequestParams(new String[] { "rtype", "pid", "utoken", "vscode", "canceBtn", "cid", "imei", "imsi" });
		button.setPageType(0);
		return button;
	}

	@Override
	public CatAppMessageResp getMessageInfo2(Integer rtype, String pid) {
		// 设置系统常规消息
		List<CatAppNotice> list = catAppNoticeRepository.findByMstatus(1);
		if (list == null || list.size() < 1) {
			return null;
		}
		// 从集合中随机抽取
		Random random = new Random();
		CatAppNoticeResp resp = new CatAppNoticeResp();
		BeanUtils.copyProperties(list.get(random.nextInt(list.size())), resp);
		// 获取商品消息
		List<CatAppGoodsMsgResp> goodsList = cacheService.getAppGoodsMesssageList(rtype);
		return CatAppMessageResp.builder().systemNotice(resp).goodsNotice(goodsList).build();
	}

	@Override
	public List<NewItemResp> getNewData(Integer rtype, String channel, String vscode, Integer pageNum,
			Integer pageSize) {
		String key = channel + "_" + pageNum + "_" + pageSize;
		return cacheService.getNewData(DigestUtils.md5DigestAsHex(key.getBytes()), channel, pageNum, pageSize);
	}

	/**
	 * 获取新手教程视频列表
	 */
	@Override
	public List<CatAppUseVideo> getUseVideo(Integer rtype, Integer id) {
		// TODO Auto-generated method stub
		// 获取视频列表
		List<CatAppUseVideo> videoList = appVideoRepository.findById(id);
		// List<CatAppUseVideo> videoList=appVideoRepository.findAll();
		if (videoList == null || videoList.size() < 1) {
			return null;
		}
		return videoList;
	}
}
